package com.itheima.aop;

import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.mapper.OperationLogMapper;
import com.itheima.pojo.OperateLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class OperateAspect {
    @Autowired
    HttpServletRequest httpServletRequest;
    @Autowired
    OperationLogMapper operationLogMapper;

    @Around("@annotation(com.itheima.anno.Log)")
    public Object OperateLogAround(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("日志记录前置通知: ");
        OperateLog operateLog = new OperateLog();//创建一个日志对象封装日志数据
        String requestURL = httpServletRequest.getRequestURL().toString();//完整url
        operateLog.setUrl(requestURL);//URL
        operateLog.setOperateTime(LocalDateTime.now());//操作时间
        long start = System.currentTimeMillis();//开始时间
        String browser = httpServletRequest.getHeader("User-Agent");//浏览器信息
        operateLog.setClientBrowser(browser);
        String operationSystem = httpServletRequest.getHeader("sec-ch-ua-platform");//操作系统
        operateLog.setClientPlatform(operationSystem);
        //operateLog.setClientPlatform(browser.substring(browser.indexOf("(") + 1, browser.indexOf(" ", browser.indexOf("("))));
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));//参数
        operateLog.setTargetClass(pjp.getTarget().getClass().getName());//目标类名
        operateLog.setTargetMethod(pjp.getSignature().getName());//方法名
        R result = (R)pjp.proceed();
        String resultJsonString = JSON.toJSONString(result);
        operateLog.setMethodReturn(resultJsonString);//方法返回值JSON字符串形式
        long end = System.currentTimeMillis();//结束时间
        operateLog.setCostTime(end - start);//耗时
        operationLogMapper.insert(operateLog);
        return result;
    }
}
